package cc.miwuya.property.controller;

import cc.miwuya.common.util.JwtUtils;
import cc.miwuya.common.util.Result;
import cc.miwuya.core.BaseController;
import cc.miwuya.property.domain.Repair;
import cc.miwuya.property.service.RepairService;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author 迷雾森林
 * @Date 2024-02-27 14:54
 * @Desc 报修控制器
 */
@RestController
@RequestMapping("/property/repair")
public class RepairController extends BaseController {

    @Resource
    RepairService repairService;
    @Resource
    HttpServletRequest httpServletRequest;

    /**
     * 报修或处理报修
     */
    @PostMapping("/edit")
    public Result edit(@RequestBody Repair repair){
        if (repair.getStatus()==1){
            repair.setOperatorId(getCurrent());
            repair.setFinish(LocalDateTime.now());
        }
        repairService.saveOrUpdate(repair);
        return Result.success();
    }

    /**
     * 获取报修列表
     */
    @GetMapping("/list")
    public Result list(String name,Long residentialId){

        return Result.success(repairService.getPage(getPage(),name,residentialId));
    }
    public Long getCurrent(){
        String authorization = httpServletRequest.getHeader("Authorization");
        Claims claim = JwtUtils.getClaimByToken(authorization, "community");
        JSON parse = JSONUtil.parse(claim);
        System.out.println(parse);
        return Long.parseLong(parse.getByPath("userId").toString());
    }

    /**
     * 获取业主的报修列表
     */
    @GetMapping("/list/{userId}")
    public Result getOwnerRepairList(String name,Long residentialId, @PathVariable String userId){
        return Result.success(repairService.getOwnerRepairList(getPage(),name,residentialId,userId));
    }
    /**
     * 获取报修数量
     */
    @GetMapping("/total")
    public Long total(){
        return repairService.count();
    }
}
